package com.xcm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.OperationLogConstant;
import com.xcm.dao.DeviceGroupMapper;
import com.xcm.exception.ServiceException;
import com.xcm.model.TbDeviceGroup;
import com.xcm.model.TbOperationLog;
import com.xcm.model.dto.DeviceGroupListDTO;
import com.xcm.model.dto.DeviceGroupTreeListDTO;
import com.xcm.service.DeviceGroupService;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.OperationLogService;
import com.xcm.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service(value = "deviceGroupService")
public class DeviceGroupServiceImpl implements DeviceGroupService {

	@Autowired
	private DeviceGroupMapper deviceGroupMapper;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private DeviceInfoService deviceInfoService;

	/**
	 * 所有终端分组列表
	 *
	 * @return List<DeviceGroupListDTO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<DeviceGroupListDTO> listAllDeviceGroup() {
		return deviceGroupMapper.listAllDeviceGroup();
	}

	/**
	 * 保存终端分组
	 *
	 * @param deviceGroup TbDeviceGroup类型对象
	 * @param user
	 * @param request
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveDeviceGroup(TbDeviceGroup deviceGroup, JSONObject user, HttpServletRequest request) throws ServiceException {
		//检查分组名是否存在
		TbDeviceGroup nameDeviceGroup = deviceGroupMapper.getDeviceGroupByGroupName(deviceGroup.getGroupName());
		if (nameDeviceGroup != null) {
			throw new ServiceException("分组名已存在,不能重复");
		}
		//检查分组码是否存在
		TbDeviceGroup codeDeviceGroup = deviceGroupMapper.getDeviceGroupByGroupCode(deviceGroup.getGroupCode());
		if (codeDeviceGroup != null) {
			throw new ServiceException("分组码已存在,不能重复");
		}
		deviceGroup.setUpdateTime(System.currentTimeMillis());
		//保存终端分组
		deviceGroupMapper.saveDeviceGroup(deviceGroup);
		//保存操作日志
		TbOperationLog operationLog = new TbOperationLog();
		operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
		operationLog.setOperationContent("添加终端分组:" + deviceGroup.getGroupName());
		operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		// TODO: 2018/4/9 处理用户ID和IP地址
		//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
		operationLog.setUserName(user.getString("userName"));
		operationLog.setRealName(user.getString("realName"));
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}


	/**
	 * 更新终端分组
	 *
	 * @param deviceGroup TbDeviceGroup类型对象
	 * @param user
	 * @param request
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateDeviceGroup(TbDeviceGroup deviceGroup, JSONObject user, HttpServletRequest request) throws ServiceException {
		// 分组主键id
		Long deviceGroupId = deviceGroup.getDeviceGroupId();
		// 分组名
		String groupName = deviceGroup.getGroupName();
		TbDeviceGroup nameDeviceGroup = deviceGroupMapper.getDeviceGroupByGroupName(groupName);
		if (nameDeviceGroup != null) {
			// 如果已存在分组名相同且主键不同，则重复
			if (groupName.equals(nameDeviceGroup.getGroupName()) && !deviceGroupId.equals(nameDeviceGroup.getDeviceGroupId()) ) {
				throw new ServiceException("分组名已存在,不能重复");
			}
		}
		// 分组码
		String groupCode = deviceGroup.getGroupCode();
		TbDeviceGroup codeDeviceGroup = deviceGroupMapper.getDeviceGroupByGroupCode(groupCode);
		if (codeDeviceGroup != null) {
			// 如果已存在分组码相同且主键不同，则重复
			if (groupCode.equals(codeDeviceGroup.getGroupCode()) && !deviceGroupId.equals(codeDeviceGroup.getDeviceGroupId())) {
				throw new ServiceException("分组码已存在,不能重复");
			}
		}
		deviceGroup.setUpdateTime(System.currentTimeMillis());
		deviceGroupMapper.updateDeviceGroup(deviceGroup);
		//保存操作日志
		TbOperationLog operationLog = new TbOperationLog();
		operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
		operationLog.setOperationContent("更新终端分组:" + deviceGroup.getGroupName());
		operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		// TODO: 2018/4/9 处理用户ID和IP地址
		//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
		operationLog.setUserName(user.getString("userName"));
		operationLog.setRealName(user.getString("realName"));
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 获取终端分组
	 *
	 * @param deviceGroupId 终端分组ID
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public TbDeviceGroup getDeviceGroup(Long deviceGroupId) {
		return deviceGroupMapper.getDeviceGroupById(deviceGroupId);
	}

	/**
	 * 删除终端分组
	 * @param deviceGroupId 终端分组ID
	 * @param groupName 终端分名称
	 * @param groupCode
	 * @param user
	 * @param request
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void deleteDeviceGroup(Long deviceGroupId, String groupName, String groupCode, JSONObject user, HttpServletRequest request) {
		//删除终端分组
		deviceGroupMapper.deleteDeviceGroupById(deviceGroupId);
		// 将所属终端的分组置为空
		deviceInfoService.updateDeviceGroupNull(groupCode);
		//保存操作日志
		TbOperationLog operationLog = new TbOperationLog();
		operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);
		operationLog.setOperationContent("删除分组：" + groupName);
		operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		// TODO: 2018/4/9 处理用户ID和IP地址
		//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
		operationLog.setUserName(user.getString("userName"));
		operationLog.setRealName(user.getString("realName"));
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过父ID获取终端分组列表
	 *
	 * @param parentId 父ID
	 * @return List<TbDeviceGroup>
	 */
	@Override
	public List<TbDeviceGroup> listDeviceGroupByParentId(Long parentId) {
		return deviceGroupMapper.listDeviceGroupByParentId(parentId);
	}


	/**
	 * 所有终端树形分组列表
	 *
	 * @return List<DeviceGroupTreeListDTO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<DeviceGroupTreeListDTO> listAllDeviceGroupTree() {
		return deviceGroupMapper.listAllDeviceGroupTree();
	}

	/**
	 * 移动终端到分组
	 * @param groupCode 分组码
	 * @param deviceInfoIds    终端id
	 * @param user
	 * @param request
	 */
    @Override
    public void moveDeviceGroup(String groupCode, String deviceInfoIds, JSONObject user, HttpServletRequest request) throws ServiceException {
    	StringBuilder logInfo = new StringBuilder("");
    	TbDeviceGroup tbDeviceGroup = deviceGroupMapper.getDeviceGroupByGroupCode(groupCode);

    	if(tbDeviceGroup == null) {
    		if(!BusinessConstant.GROUP_CODE_ALL_DEVICE.equals(groupCode)) {
				throw new ServiceException("所选分组不存,请刷新后重试");
			}
			// 目标分组是“全部分组”，则对应分组编码为空
			groupCode = null;
			logInfo.append("全部分组");
		}else {
			logInfo.append(tbDeviceGroup.getGroupName());
		}

		for(String deviceInfoId : deviceInfoIds.split(",")) {
			deviceGroupMapper.moveDeviceGroup(groupCode,deviceInfoId);
		}
		//保存操作日志
		TbOperationLog operationLog = new TbOperationLog();
		operationLog.setOperationTypeId(OperationLogConstant.OPERATION_LOG_TYPE_DEVICE);

		operationLog.setOperationContent("移动id=" + deviceInfoIds + "的终端到分组:" + logInfo);
		operationLog.setIsSuccess(OperationLogConstant.OPERATION_LOG_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		// TODO: 2018/4/9 处理用户ID和IP地址
		//展示设置操作用户名、用户真实姓名、IP为空，用户保存在统一登录系统
		operationLog.setUserName(user.getString("userName"));
		operationLog.setRealName(user.getString("realName"));
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
    }
}
